<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace weapp\ErxClose\logic;

use think\Db;

/**
 * 业务逻辑
 */
class ErxCloseLogic
{
    public function __construct($config = []) {
        
    }
        /**
     * 判断是否搜索引擎机器人或者爬行蜘蛛
     * @param 
     * @access public
     */    
    public function isRobot() {
        $agent= strtolower(isset($_SERVER['HTTP_USER_AGENT'])? $_SERVER['HTTP_USER_AGENT'] : '');
        if(!empty($agent)){
            $spiderSite= array("TencentTraveler","Baiduspider+","BaiduGame","Googlebot","msnbot","Sosospider+","Sogou web spider","ia_archiver","Yahoo! Slurp","YoudaoBot","Yahoo Slurp","MSNBot","Java (Often spam bot)","BaiDuSpider","Voila","Yandex bot","BSpider","twiceler","Sogou Spider","Speedy Spider","Google AdSense","Heritrix","Python-urllib","Alexa (IA Archiver)","Ask","Exabot","Custo","OutfoxBot/YodaoBot","yacy","SurveyBot","legs","lwp-trivial","Nutch","StackRambler","The web archive (IA Archiver)","Perl tool","MJ12bot","Netcraft","MSIECrawler","WGet tools","larbin","Fish search","360spider","msn","Bingbot","shenma","sm","sogou","360"
            );
            foreach($spiderSite as $val){
                $str = strtolower($val);
                    if(strpos($agent, $str) !== false){
                        return true;
                }
            }
        }
        return false;
    }
    /**
     *  业务流程
     * @param 
     * @access public
     */

    public function todo($data){       
        if(!empty($data['is_link']) && self::links($data['is_link'])!==false){ // 自定义赦免站点             
            return true;
        }
        if(!empty($data['is_open_url']) && self::loclinks($data['is_open_url'])!==false){ // 自定义赦免站点             
            return true;
        }
        if($data['is_seo']==1 && self::isRobot()!==false){  // 允许蜘蛛爬虫                 
            return true;
        }       
        if($data['is_dev']==1 && self::isMobile()){ // 允许移动端访问            
            return true;
        }
        if($data['is_times']==1){ // 关闭时间段         
            if ($this->isCurrentTimeInRange($data['starttime'], $data['endtime'])){ //关闭时间段内            
            }else{
                return true;
            }
        }
        return  self::setCode($data);
    }
    /**
     *  判断时间是否在时间段内
     * @Author    非洲和尚
     * @DateTime  2024-12-24
     * @copyright [copyright]
     * @license   [license]
     * @version   [version]
     * @param     [type]      $startTime [description]
     * @param     [type]      $endTime   [description]
     * @return    boolean                [description]
     */
    function isCurrentTimeInRange($startTime, $endTime)
    {
        $nowTime = (int)date('H');
        // 获取当前时间的时间戳
        $currentTime = strtotime(date('Y-m-d').' '. $nowTime.":00");
        $startTime = ($startTime < 10)? "0{$startTime}" :$startTime;
        $endTime = ($endTime < 10)? "0{$endTime}" :$endTime; 
        // 将传入的开始时间和结束时间字符串转换为当天对应的时间戳
        $startTimestamp = strtotime(date('Y-m-d').' '. $startTime.":00");
        $endTimestamp = strtotime(date('Y-m-d').' '. $endTime.":00");

        // 如果结束时间小于开始时间，说明跨天了，需要把结束时间设置为第二天的对应时间
        if ($endTimestamp <= $startTimestamp) {
            $endTimestamp = strtotime('+1 day', $endTimestamp);
        }

        // 判断当前时间是否在区间内
        return ($currentTime >= $startTimestamp && $currentTime < $endTimestamp);
    }

    /**
     * 
     */
    public function setDo(){

    }
    /**
     *  判断是否移动端
     * @param 
     * @access public
     */
    public function isMobile()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $mobile_agents = array("240x320", "acer", "acoon", "acs-", "abacho", "ahong", "airness", "alcatel", "amoi", "android", "anywhereyougo.com", "applewebkit/525", "applewebkit/532", "asus", "audio", "au-mic", "avantogo", "becker", "benq", "bilbo", "bird", "blackberry", "blazer", "bleu", "cdm-", "compal", "coolpad", "danger", "dbtel", "dopod", "elaine", "eric", "etouch", "fly ", "fly_", "fly-", "go.web", "goodaccess", "gradiente", "grundig", "haier", "hedy", "hitachi", "htc", "huawei", "hutchison", "inno", "ipad", "ipaq", "ipod", "jbrowser", "kddi", "kgt", "kwc", "lenovo", "lg ", "lg2", "lg3", "lg4", "lg5", "lg7", "lg8", "lg9", "lg-", "lge-", "lge9", "longcos", "maemo", "mercator", "meridian", "micromax", "midp", "mini", "mitsu", "mmm", "mmp", "mobi", "mot-", "moto", "nec-", "netfront", "newgen", "nexian", "nf-browser", "nintendo", "nitro", "nokia", "nook", "novarra", "obigo", "palm", "panasonic", "pantech", "philips", "phone", "pg-", "playstation", "pocket", "pt-", "qc-", "qtek", "rover", "sagem", "sama", "samu", "sanyo", "samsung", "sch-", "scooter", "sec-", "sendo", "sgh-", "sharp", "siemens", "sie-", "softbank", "sony", "spice", "sprint", "spv", "symbian", "tablet", "talkabout", "tcl-", "teleca", "telit", "tianyu", "tim-", "toshiba", "tsm", "up.browser", "utec", "utstar", "verykool", "virgin", "vk-", "voda", "voxtel", "vx", "wap", "wellco", "wig browser", "wii", "windows ce", "wireless", "xda", "xde", "zte");
        $is_mobile = false;
        foreach ($mobile_agents as $device) {
            if (stristr($user_agent, $device)) {
                return true;
                break;
            }
        }
        return false;
    } 
    /**
     *  网站状态
     * @param 
     * @access public
     */
    public function setCode($row){
        switch ($row['is_tig']) {
            case 1:
                // 提示文案                
                die(self::errorhtml($row));                
                break;
            case 2:
                //  404响应                 
                header('HTTP/1.1 404 Not Found');                
                $hml =<<<EOF
<!DOCTYPE html>
                <html><head>
                <title>404 Not Found</title>
                </head><body>
                <h1>Not Found</h1>
                <p>The requested URL /2 was not found on this server.</p>
                <p>Additionally, a 404 Not Found
                error was encountered while trying to use an ErrorDocument to handle the request.</p>
                </body></html>
EOF;
                die($hml);
                exit();
                break;
            case 3:
                //404页面      
                return  abort(404,'页面不存在');                                
                break;   
            case 4:
                // 403响应                
                return  abort(403,'页面不存在');                                
                break;  
            case 6:
                //自定义跳转
                $is_url = htmlspecialchars_decode($row['is_url']);
                header('Location: '.$is_url.'');
                break;          
            default:                
               return  abort(503,'页面不存在');                        
            break;
        }
    }
    /**
     *  本地赦免站点
     * @param 
     * @access public
     */
    public function loclinks($row){              
        $referer ='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];        
        $isFromFriendlyLink = false;            
        $is_open_url =  nl2br($row);
        $allowed_domains = explode('<br />',$is_open_url); 
        foreach ($allowed_domains as $key => $value) {
            $datas[] = trim($value);
        }   
        if (in_array($referer, $datas)) {                    
           $isFromFriendlyLink = true;
        }     
        if ($isFromFriendlyLink) {
            return true;            
        } else {
            return false;
        }
    }
    /**
     * 赦免自定义站点
     * @param 
     * @access public
     */
    public function links($is_link){
        $referer = $_SERVER['HTTP_REFERER'] ?? ''; // 获取Referer头信息
        $isFromFriendlyLink = false;                         
        $allowed_domains = explode('|',$is_link);                                                
        foreach ($allowed_domains as $domain) {
            if (strpos($referer, $domain) !== false) {
                $isFromFriendlyLink = true;
                break;
            }
        }         
        if ($isFromFriendlyLink) {
            return true;            
        } else {
            return false;
        }        
    }
    /**
     * 提示文案
     * @param 
     * @access public
     */    
    public function errorhtml($row){
        if($row['content']){        
            $content = htmlspecialchars_decode($row['content']);
            $titlesource_html =<<<EOF
<!DOCTYPE html>
            <html>
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1">
                <title>{$row['web_name']}</title>
            </head>
            <body>
            <div class="content">
            {$content}
            </div>            
            </body>
            </html>
EOF;
            return $titlesource_html;
        }
    }
}
